package com.usian.security.handler;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.usian.common.model.Result;
import com.usian.security.utils.WebUtil;
import org.apache.catalina.connector.Response;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: AuthenticationEntryPointHndler
 * Author:   WGG
 * Date:    2022-12-2022/12/21-15:38
 * Version: 1.0
 * Description:
 */

/**
 * 认证过程中失败，捕获到异常，封装成统一的响应体格式返回
 */
@Component
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Result<Object> result = Result.createError(HttpStatus.HTTP_UNAUTHORIZED, "认证失败请重新登录");
        String jsonString = JSON.toJSONString(result);
        WebUtil.renderString(response,jsonString);
    }
}
